<?php
/**
 * 商品逻辑
 * 作者：MYL
 */
namespace app\api\controller;

use think\Db;

class Goods extends Base
{
    /** --------------------------------优惠券模块--------------------------------------------- */
    /**
     * 优惠券个人列表（下单）
     */
    public function couponUser()
    {
        $user_id = I('post.user_id');
        $categoryId = I('post.cid'); //商品的分类ID
        $page = I("page", 1);//分页数

        //判断优惠券是否失效
        $result = M("coupon_exchange")->whereTime('send_end_time','<',time())->where("status=0")->select();
        foreach ($result as $val) {
            M("coupon_exchange")->where("id",$val['id'])->update(['status'=>2]); //状态 0.未使用 1.已使用 2.已过期
        }
        //查询当前商品分类的ID（前2级ID）
        $fid = getPrent($categoryId);
        //获取当前商品分类的 儿子 孙子  重子重孙 的 id
        $arr = getCatGrandson($categoryId); //获取某个商品分类的 儿子 孙子  重子重孙 的 id
        $parentNum = array_merge($fid,$arr);
        //获取有效的优惠券
        $row = M("coupon")->alias('c')
            ->join('vip_coupon_exchange ce','c.id=ce.cid')
            ->join('vip_goods_coupon gc','c.id=gc.coupon_id')
            ->field("c.*,ce.user_id,ce.status as esattus,FROM_UNIXTIME(ce.send_end_time,'%Y%m%d') as send_end_time,gc.goods_category_id")
            ->where("ce.status=0")
            ->where('ce.user_id',$user_id)
            ->where("gc.goods_category_id", "IN", $parentNum)
            ->page($page, 20)
            ->select();
        foreach ($row as $key => $val) {
            if ($val['use_type']==0) {
                $row[$key]['use_type'] = '全店通用';
            } elseif ($val['use_type']==2) { //指定分类商品可用
                //获取优惠券指定分类ID
                //$fen = M("goods_coupon")->field("goods_category_id")->where("coupon_id",$val['id'])->find();
                $fen_name = M("goods_category")->field("name")->where("id",$val['goods_category_id'])->find();
                $row[$key]['use_type'] = $fen_name['name'];
            }
//            $row[$key]['send_end_time'] = date("Y-m-d H:i:s",$val['send_end_time']);
//            if ($val['status']==1) {
//                $row[$key]['status'] = '有效';
//            } else {
//                $row[$key]['status'] = '无效';
//            }
//            if ($val['estatus']==0) {
//                $row[$key]['estatus'] = '未使用';
//            } elseif ($val['estatus']==1) {
//                $row[$key]['estatus'] = '已使用';
//            } else {
//                $row[$key]['estatus'] = '已过期';
//            }
        }
        if (!empty($row)) {
            ajaxReturn(['status' => 1, 'msg' => '获取成功！', 'result' => $row]);
        } else {
            ajaxReturn(['status' => -1, 'msg' => '获取失败！', 'result' => []]);
        }
    }

    /**
     * 优惠券兑换记录
     */
    public function coupon_record()
    {
        $user_id = I('post.user_id');
        $page = I("page", 1);//分页数

        //获取有效的优惠券
        $row = M("coupon")->alias('c')
            ->join('vip_coupon_exchange ce','c.id=ce.cid')
            ->field("c.*,ce.user_id,ce.status as esattus,FROM_UNIXTIME(ce.send_start_time,'%Y%m%d') as send_start_time")
            ->where("ce.status=0")
            ->where('ce.user_id',$user_id)
            ->page($page, 20)
            ->select();
        foreach ($row as $key => $val) {
            if ($val['use_type']==0) {
                $row[$key]['use_type'] = '全店通用';
            } elseif ($val['use_type']==2) { //指定分类商品可用
                //获取优惠券指定分类ID
                $fen = M("goods_coupon")->field("goods_category_id")->where("coupon_id",$val['id'])->find();
                $fen_name = M("goods_category")->field("name")->where("id",$fen['goods_category_id'])->find();
                $row[$key]['use_type'] = $fen_name['name'];
            }
        }
        if (!empty($row)) {
            ajaxReturn(['status' => 1, 'msg' => '获取成功！', 'result' => $row]);
        } else {
            ajaxReturn(['status' => -1, 'msg' => '获取失败！', 'result' => []]);
        }
    }

    /**
     * 优惠券兑换列表
     */
    public function couponList()
    {
        $page = I("page", 1);//分页数

        $row = M("coupon")
            ->where("status=1")
            ->page($page, 20)
            ->select();
        foreach ($row as $key => $val) {
            if ($val['use_type']==0) {
                $row[$key]['use_type'] = '全店通用';
            } elseif ($val['use_type']==2) { //指定分类商品可用
                //获取优惠券指定分类ID
                $fen = M("goods_coupon")->field("goods_category_id")->where("coupon_id",$val['id'])->find();
                $fen_name = M("goods_category")->field("name")->where("id",$fen['goods_category_id'])->find();
                $row[$key]['use_type'] = $fen_name['name'];
            }
            $row[$key]['send_end_time'] = date("Y-m-d H:i:s",$val['send_end_time']);
            if ($val['status']==1) {
                $row[$key]['status'] = '有效';
            } else {
                $row[$key]['status'] = '无效';
            }
        }
        if (!empty($row)) {
            ajaxReturn(['status' => 1, 'msg' => '获取成功！', 'result' => $row]);
        } else {
            ajaxReturn(['status' => -1, 'msg' => '获取失败！', 'result' => []]);
        }
    }

    /**
     * 优惠券兑换
     */
    public function couponAdd()
    {
        $user_id = I('post.user_id');
        $cid = I('post.cid');  //优惠券ID
        $money = I('post.money');  //优惠金额
        $condition = I('post.condition');  //优惠券所需的积分

        $thirty = strtotime(date('Y-m-d H:i:s', strtotime("30 day"))); //30天后的今天
        $data['user_id'] = $user_id;
        $data['cid'] = $cid;
        $data['money'] = $money;
        $data['integral'] = $condition;
        $data['send_start_time'] = time();
        $data['send_end_time'] = $thirty;
        $data['status'] = 0;

        //判断用户是否领取过优惠券（未使用，未过期的优惠券）
        $isExchange= M('coupon_exchange')->field('id')->where(['user_id'=>$user_id, 'cid'=>$cid,'status'=>0])->find();
        if (!empty($isExchange)) {
            ajaxReturn(['status' => -1, 'msg' => '您已经兑换过了,请先使用！']);
        }
        $row = M('users')->field('pay_points')->where('user_id',$user_id)->find();
        if ($row['pay_points'] < $condition) {
            ajaxReturn(['status' => -1, 'msg' => '您的积分不够,无法兑换！']);
        }
        $rs = M('coupon_exchange')->insert($data); //添加兑换记录
        if (!empty($rs)) {
            $pay_points = $row['pay_points'] - $condition;
            $result = M('users')->where('user_id',$user_id)->update(['pay_points'=>$pay_points]); //修改新的积分
            if ($result) {
                $mag['user_id'] = $user_id;
                $mag['pay_points'] = '-' . $condition;
                $mag['change_time'] = time();
                $mag['order_sn'] = '';
                $mag['order_id'] = 0;
                $mag['desc'] = '积分兑换优惠券';
                M('account_log')->insert($mag);
                ajaxReturn(['status' => 1, 'msg' => '兑换成功！']);
            } else {
                ajaxReturn(['status' => -1, 'msg' => '积分扣除失败！']);
            }
        } else {
            ajaxReturn(['status' => -1, 'msg' => '兑换失败！']);
        }
    }

    /** --------------------------------商品模块--------------------------------------------- */
    /**
     * 商品一级导航和二级
     */
    public function all_category()
    {
        $all_category = M('goods_category')->field('id,name,image')->where("level=1 and is_show=1")->select();
        foreach ($all_category as $key => $val) {
            $second_level = M('goods_category')->field('id,name')->where(["parent_id" => $val['id']])->select();
            $all_category[$key]['son'] = $second_level;
        }
        if (!empty($all_category)) {
            ajaxReturn(['status' => 1, 'msg' => '获取成功！', 'result' => $all_category]);
        } else {
            ajaxReturn(['status' => -1, 'msg' => '获取失败！', 'result' => []]);
        }
    }

    /**
     * 通过分类ID查询子集的名称
     */
    public function category_subset()
    {
        $category_id = I("post.category_id");//分类ID

        $all_category = M('goods_category')->field('id,name')->where("is_show=1")->where('parent_id',$category_id)->select();
        if (!empty($all_category)) {
            ajaxReturn(['status' => 1, 'msg' => '获取成功！', 'result' => $all_category]);
        } else {
            ajaxReturn(['status' => -1, 'msg' => '获取失败！', 'result' => []]);
        }
    }

    /**
     *  通过分类ID查询所有商品列表
     */
    public function all_sons()
    {
        $category_id = I("category_id");//分类ID
        $page = I("page", 1);//分页数
        $arr = getCatGrandson($category_id); //获取某个商品分类的 儿子 孙子  重子重孙 的 id
        $data = M('goods')->field('goods_id,cat_id,goods_sn,goods_remark,goods_name,original_img,sales_sum,shop_price')
            ->where("cat_id", "IN", $arr)
            ->page($page, 10)
            ->select();
        $cat_name = Db::name('goods_category')->field('name')->where('id',$category_id)->find();
        if (!empty($data)) {
            ajaxReturn(['status' => 1, 'msg' => '获取成功！', 'result' => $data, 'cat_name' => $cat_name['name']]);
        } else {
            ajaxReturn(['status' => -1, 'msg' => '获取失败！', 'result' => []]);
        }
    }

    /**
     * 查询一级下的子集
     * @param $a
     * @param $pid
     * @return array
     */
    public function get_attrs($a, $pid)
    {
        $tree = array(); //每次都声明一个新数组用来放子元素
        foreach ($a as $v) {
            if ($v['parent_id'] == $pid) //匹配子记录
            {
                $v['children'] = $this->get_attrs($a, $v['id']); //递归获取子记录
                if ($v['children'] == null) {
                    unset($v['children']); //如果子元素为空则unset()进行删除，说明已经到该分支的最后一个元素了（可选）
                }
                $tree[] = $v; //将记录存入新数组
            }
        }
        return $tree; //返回新数组
    }

    /**
     * 商品详情页
     */
    public function goods_details()
    {
        $goods_id = I("post.goods_id/d");
        $Goods = new \app\common\model\Goods();
        $goods = $Goods::get($goods_id);
        if (empty($goods) || ($goods['is_on_sale'] == 0)) {
            ajaxReturn(['status' => -1, 'msg' => '该商品已经下架！']);
        }
        $goods['goods_content'] = htmlspecialchars_decode($goods['goods_content']);
        $filter_spec = $this->get_specs($goods_id);//规格参数
        $spec_goods_price = M('spec_goods_price')->field('key,item_id,key_name,price,store_count,market_price')->where("goods_id", $goods_id)->select(); //规格 对应 价格 库存表
        ajaxReturn(['status' => 1, 'msg' => 'success', 'goods' => $goods, 'filter_spec' => $filter_spec, 'spec_goods_price' => $spec_goods_price]);
    }

    /**
     * 获取商品规格
     * @param $goods_id |商品id
     * @return array
     */
    public function get_specs($goods_id)
    {
        //商品规格 价钱 库存表 找出 所有 规格项id
        $keys = M('SpecGoodsPrice')->where("goods_id", $goods_id)->getField("GROUP_CONCAT(`key` ORDER BY store_count desc SEPARATOR '_') ");
        $filter_spec = array();
        if ($keys) {
            $specImage = M('SpecImage')->where(['goods_id' => $goods_id, 'src' => ['<>', '']])->getField("spec_image_id,src");// 规格对应的 图片表， 例如颜色
            $keys = str_replace('_', ',', $keys);
            $sql = "SELECT a.name,a.order,b.* FROM __PREFIX__spec AS a INNER JOIN __PREFIX__spec_item AS b ON a.id = b.spec_id WHERE b.id IN($keys) ORDER BY b.id";
            $filter_spec2 = \think\Db::query($sql);
            foreach ($filter_spec2 as $key => $val) {
                $filter_spec[$val['name']][] = array(
                    'item_id' => $val['id'],
                    'item' => $val['item'],
                    'src' => $specImage[$val['id']],
                );
            }
            foreach ($filter_spec as $key2 => $vv) {
                $filter_spec3[] = array(
                    "key" => $key2,
                    "value" => $vv
                );
            }
        }
        return $filter_spec3;
    }

    /** --------------------------------地址模块--------------------------------------------- */
    /**
     * 获取用户的地址列表
     */
    public function address_list()
    {
        if (IS_POST) {
            $user_id = I("post.user_id");
            $row = M('user_address')->where("user_id",$user_id)->order('is_default desc')->select();
            foreach ($row as $key =>$val) {
                $add = Db::name('region')->field('name')->where('id',$val['province'])->find();
                $row[$key]['province'] = $add['name'];
                $add2 = Db::name('region')->field('name')->where('id',$val['city'])->find();
                $row[$key]['city'] = $add2['name'];
                $add3 = Db::name('region')->field('name')->where('id',$val['district'])->find();
                $row[$key]['district'] = $add3['name'];
                $row[$key]['address'] = $add['name'].$add2['name'].$add3['name'].$val['address'];
            }
            if ($row) {
                ajaxReturn(['status' => 1, 'msg' => '查询成功', 'result' => $row]);
            } else {
                ajaxReturn(['status' => -1, 'msg' => '查询失败', 'result' => []]);
            }
        } else {
            ajaxReturn(['status' => -1, 'msg' => '操作失败，请填写内容！']);
        }
    }

    /**
     * 获取一条地址的数据
     */
    public function addressOne()
    {
        if (IS_POST) {
            $address_id = I("post.address_id");
            $row = M("user_address")->where("address_id",$address_id)->find();

            $add = Db::name('region')->field('name')->where('id',$row['province'])->find();
            $row['province'] = $add['name'];
            $add2 = Db::name('region')->field('name')->where('id',$row['city'])->find();
            $row['city'] = $add2['name'];
            $add3 = Db::name('region')->field('name')->where('id',$row['district'])->find();
            $row['district'] = $add3['name'];
            $row['region'] = $add['name'].','.$add2['name'].','.$add3['name'];
            $row['region2'] = $add['name'].$add2['name'].$add3['name'].$row['address'];

            if ($row) {
                ajaxReturn(['status' => 1, 'msg' => 'Success！', "result" => $row]);
            }
            ajaxReturn(['status' => -1, 'msg' => '获取失败！']);
        } else {
            ajaxReturn(['status' => -1, 'msg' => '操作失败，请填写内容！']);
        }
    }

    /**
     * 获取地区的（省，市，区）
     */
    public function regionOne()
    {
        if (IS_POST) {
            $address_id = I("post.address_id");
            $row = M("user_address")->field('province,city,district')->where("address_id",$address_id)->find();
            if ($row) {
                ajaxReturn(['status' => 1, 'msg' => 'Success！', "result" => $row]);
            } else {
                ajaxReturn(['status' => -1, 'msg' => '获取失败！']);
            }
        } else {
            ajaxReturn(['status' => -1, 'msg' => '操作失败，请填写内容！']);
        }
    }

    /**
     * 保存地址 新增 和 修改
     */
    public function addressSave()
    {
        if (IS_POST) {
            $data = I("post.");
            $map['user_id'] = $data['user_id'];
            $map['consignee'] = $data['consignee']; //收货人
            $map['province'] = $data['province']; //省份
            $map['city'] = $data['city']; //城市
            $map['district'] = $data['district']; //地区
            $map['twon'] = I("post.twon",0); //乡镇
            $map['zipcode'] = $data['zipcode']; //邮编
            $map['address'] = $data['address']; //详细地址
            $map['company_name'] = $data['company_name']; //公司名称
            $map['mobile'] = $data['mobile'];

            $addressId = I("post.addressId"); //地址ID

            //新增
            if (empty($addressId)) {
                $moren = M("user_address")->where("user_id",$map['user_id'])->find();
                if ($moren) $map['is_default'] = 0; else $map['is_default'] = 1;
                $row = M("user_address")->insert($map);
                if ($row) {
                    ajaxReturn(['status' => 1, 'msg' => '新增成功！']);
                } else {
                    ajaxReturn(['status' => -1, 'msg' => '新增失败，请重新填写地址！']);
                }
            } else {
                //修改
                $address_id = I("post.addressId"); //地址ID
                $row = M("user_address")->where("address_id",$address_id)->update($map);
                if ($row) {
                    ajaxReturn(['status' => 1, 'msg' => '更新成功！']);
                } else {
                    ajaxReturn(['status' => -1, 'msg' => '更新失败，请重新填写地址！']);
                }
            }
        } else {
            ajaxReturn(['status' => -1, 'msg' => '操作失败，请填写内容！']);
        }
    }

    /**
     * 设置默认地址
     */
    public function addressSetDefault()
    {
        if (IS_POST) {
            $address_id = I("post.address_id");
            M("user_address")->where("is_default",1)->update(["is_default"=>0]);
            $row = M("user_address")->where("address_id",$address_id)->update(["is_default"=>1]);
            if ($row) {
                ajaxReturn(['status' => 1, 'msg' => '设置成功']);
            }
            ajaxReturn(['status' => -1, 'msg' => '设置失败']);
        } else {
            ajaxReturn(['status' => -1, 'msg' => '操作失败，请填写内容！']);
        }
    }

    /**
     * 地址删除
     */
    public function addressDelete()
    {
        if (IS_POST) {
            $address_id = I("post.address_id");
            $row = M("user_address")->where("address_id",$address_id)->delete();
            if ($row) {
                ajaxReturn(['status' => 1, 'msg' => '删除成功']);
            }
            ajaxReturn(['status' => -1, 'msg' => '删除失败']);
        } else {
            ajaxReturn(['status' => -1, 'msg' => '操作失败，请填写内容！']);
        }
    }
}